package syllabus.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import syllabus.commons.DateTypeEditor;
import syllabus.commons.ExtGridReturn;
import syllabus.commons.ExtPager;
import syllabus.commons.ExtReturn;
import syllabus.model.Criteria;
import syllabus.model.PCourse;
import syllabus.model.PFile;
import syllabus.model.PSyllabus;
import syllabus.service.PFileService;
import syllabus.service.PSyllabusService;

@RequestMapping("/syllabus")
@Controller
public class SyllabusAct {

	public static final Logger logger = LoggerFactory.getLogger(SyllabusAct.class);
	
	@Autowired
	private PSyllabusService syllabusService;
	@Autowired
	private PFileService fileService;
	
	@InitBinder
	public void initBinder(WebDataBinder binder) {
		binder.registerCustomEditor(Date.class, new DateTypeEditor());
		binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
	}
	
	@RequestMapping("/list")
	public String list(){
		return "/syllabus/list";
	}
	
/*	@RequestMapping(value = "/save", method = RequestMethod.POST)
	@ResponseBody
	public Object saveUpload(PSyllabus syllabus){
		ExtReturn ext = new ExtReturn();
		Integer id = syllabus.getId();
		if( null != id){
			PSyllabus ps = syllabusService.selectByPrimaryKey(id);
			ps.setFilename(syllabus.getFilename());
			ps.setLink(syllabus.getLink());
			syllabusService.updateByPrimaryKeySelective(ps);
			ext.setSuccess(ExtReturn.SUCCESS);
			ext.setMsg("上传成功");
		}else{
			ext.setSuccess(ExtReturn.FAILURE);
			ext.setMsg("上传失败");
		}
		
		return ext;
	}*/
	
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public void saveUpload(PSyllabus syllabus,String attachId,HttpServletResponse response){
		ExtReturn ext = new ExtReturn();
		Integer id = syllabus.getId();
		if( null != id && StringUtils.isNotBlank(attachId)){
			PSyllabus ps = syllabusService.selectByPrimaryKey(id);
			//ps.setFilename(syllabus.getFilename());
			//ps.setLink(syllabus.getLink());
			//syllabusService.updateByPrimaryKeySelective(ps);
			
			//更新附件p_file表syllabus_id，关联大纲表
			PFile pf = fileService.selectByPrimaryKey(Integer.parseInt(attachId));
			pf.setSyllabusId(ps.getId());
			fileService.updateByPrimaryKeySelective(pf);
			
			ext.setSuccess(ExtReturn.SUCCESS);
			ext.setMsg("上传成功");
		}else{
			ext.setSuccess(ExtReturn.FAILURE);
			ext.setMsg("上传失败");
		}
		
		response.setContentType("text/plain;charset=utf-8");
		ObjectMapper om = new ObjectMapper();
		try {
			om.writeValue(response.getWriter(),ext );
		} catch (JsonGenerationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	@RequestMapping(value = "/all", method = RequestMethod.POST)
	@ResponseBody
	public Object all(ExtPager pager,@RequestParam(required = false,value = "syllabusName")String syllabusName,
			HttpServletRequest request,ModelMap map) {

		Criteria criteria = new Criteria();
		// 设置分页信息
		if (pager.getPage() != null && pager.getRows() != null) {
			criteria.setPage(pager.getPage());
			criteria.setPageSize(pager.getRows());
		}
		// 排序信息
		if (StringUtils.isNotBlank(pager.getOrder())
				&& StringUtils.isNotBlank(pager.getSort())) {
			criteria.setOrderByClause(pager.getSort() + " " + pager.getOrder());
		}
		if (StringUtils.isNotBlank(syllabusName)) {
			criteria.put("syllabusNameLike", syllabusName);
		}
		
		List<PSyllabus> list = this.syllabusService.selectByExample(criteria);

		int total = this.syllabusService.countByExample(criteria);
		return new ExtGridReturn(total, list);
	}
	
	@RequestMapping(value = "/getdetail/{itemId}", method = RequestMethod.POST)
	@ResponseBody
	public Object getdetail(@PathVariable("itemId")String itemId){
		Criteria c = new Criteria();
		if(StringUtils.isNotBlank(itemId)){
			c.put("syllabusId", itemId);
			List<PFile> list = fileService.selectByExample(c);
			return list;
		}else{
			return null;
		}
		
		
	}
	
	@RequestMapping(value = "/merge", method = RequestMethod.POST)
	public void merge(String kcdm,String merge_kcdm,HttpServletResponse response) throws JsonGenerationException, JsonMappingException, IOException{
		ExtReturn ext = new ExtReturn();
		/*Criteria criteria = new Criteria();
		criteria.put("kcdm", kcdm);
		syllabusService.selectByExample(criteria);*/
		boolean result = syllabusService.mergeSyllabus(kcdm,merge_kcdm);
		if(result){
			ext.setMsg("合并成功！");
			ext.setSuccess(ExtReturn.SUCCESS);
		}else{
			ext.setMsg("合并失败！");
			ext.setSuccess(ExtReturn.FAILURE);
		}
		
		response.setContentType("text/plain;charset=utf-8");
		ObjectMapper om = new ObjectMapper();
		om.writeValue(response.getWriter(),ext );
	}
	
	@RequestMapping(value = "/combox", method = RequestMethod.POST)
	@ResponseBody
	public Object combox(String keyword){
		//ExtReturn ext = new ExtReturn();
		Criteria criteria = new Criteria();
		if (StringUtils.isNotBlank(keyword)) {
			criteria.put("syllabusNameLike", keyword);
		}
		
		List<PSyllabus> list = this.syllabusService.selectByExample(criteria);
		List<Title> returnList = new ArrayList<Title>();
		for(PSyllabus ps : list){
			Title t = new Title();
			t.setTitle(ps.getKcmc() + "--" + ps.getKcdm());
			t.setResult(ps.getKcdm());
			returnList.add(t);
		}
		return new AutoCompleteReturn(returnList);
	}
	
	class Title{
		private String title;
		private Object result;

		public String getTitle() {
			return title;
		}

		public void setTitle(String title) {
			this.title = title;
		}

		public Object getResult() {
			return result;
		}

		public void setResult(Object result) {
			this.result = result;
		}
		
	}
	
	class AutoCompleteReturn{
		private List<?> data;
		
		public AutoCompleteReturn(List<?> data){
			this.data = data;
		}

		public List<?> getData() {
			return data;
		}

		public void setData(List<?> data) {
			this.data = data;
		}

	}
}
